package com.zw.commons.security.config;/*
 *@program:java-cloud-prevalence
 *@author:zw
 *@Time: 2022/12/10
 *@description: Security配置类
 */

import com.zw.api.LogFeignClient;
import com.zw.api.UserFeignClient;
import com.zw.commons.security.custom.CustomMd5Password;
import com.zw.commons.security.custom.UserDetailsServiceImpl;
import com.zw.commons.security.filter.TokenAuthenticationFilter;
import com.zw.commons.security.filter.TokenLoginFilter;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Configuration
@EnableWebSecurity
@Slf4j
@RequiredArgsConstructor
@EnableGlobalMethodSecurity(prePostEnabled = true)  //开启基于方法的安全认证机制，也就是说在web层的controller启用注解机制的安全确认
@EnableFeignClients(basePackages = {"com.zw.api"})
public class WebSecurityConfig extends WebSecurityConfigurerAdapter implements RequestInterceptor {

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private UserDetailsServiceImpl userDetailsService;
//    private UserDetailsService userDetailsService;

    @Resource
    private CustomMd5Password customMd5PasswordEncoder;

    @Autowired
    private LogFeignClient logFeignClient;


    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 这是配置的关键，决定哪些接口开启防护，哪些接口绕过防护
        http
                //关闭csrf
                .csrf().disable()
                // 开启跨域以便前端调用接口
                .cors().and()
                .authorizeRequests()
                // 指定某些接口不需要通过验证即可访问。登陆接口肯定是不需要认证的
                .antMatchers("/admin/system/index/login"
                        ,"/admin/system/sysUser/user"
                        ,"/admin/system/sysMenu/feignFindUserMenuList"
                        ,"/admin/system/logLogin/feignLogLogin").permitAll()
                // 这里意思是其它所有接口需要认证才能访问
                .anyRequest().authenticated()
                .and()
                //TokenAuthenticationFilter放到UsernamePasswordAuthenticationFilter的前面，这样做就是为了除了登录的时候去查询数据库外，其他时候都用token进行认证。
                .addFilterBefore(new TokenAuthenticationFilter(redisTemplate), UsernamePasswordAuthenticationFilter.class)
                .addFilter(new TokenLoginFilter(authenticationManager(), redisTemplate,logFeignClient));

        //禁用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 指定UserDetailService和加密器
        auth.userDetailsService(userDetailsService).passwordEncoder(customMd5PasswordEncoder);
    }

    /**
     * 配置哪些请求不拦截
     * 排除swagger相关请求
     * @param web
     * @throws Exception
     */
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/favicon.ico","/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/doc.html",
                "/user-service/v2/**","/log-service/v2/**");
    }

    /**
     *                          feign調用時將token傳遞
     * @param requestTemplate   request
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        ServletRequestAttributes attributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("WebSecurityConfig.apply业务结束,结果:{}",request.getHeader("token"));
        //添加token
        requestTemplate.header("token", request.getHeader("token"));
    }
}
